package com.mysite.websocket.ws;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

	@Autowired
	private WebSocketHandler webSocketHandler;

	@Autowired
	private HandshakeInterceptor handshakeInterceptor;

	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(webSocketHandler, "/websocket").addInterceptors(handshakeInterceptor);
		registry.addHandler(webSocketHandler, "/websocket/sockjs").addInterceptors(handshakeInterceptor).withSockJS();
	}

	@Bean
	public ServletServerContainerFactoryBean servletServerContainerFactoryBean() {
		ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
		// 设置接收消息的最大值，超过此数值会导致连接断开
		container.setMaxTextMessageBufferSize(8192);
		container.setMaxBinaryMessageBufferSize(20480);
		return container;
	}
}
